package com.cos.utils.obj;

import com.cos.config.cons.ConstantAttribute;
import com.cos.config.COSConfig;
import com.cos.config.thread.pool.COSTaskThreadPool;
import com.cos.config.thread.task.UDTransferProgress;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.transfer.*;

import java.io.File;
import java.util.concurrent.*;

/**
 * @author Irving
 * @create 2021/7/14
 * @desc COS的对象操作
 **/
public class COSObjectDownload {

    public void download(StringBuffer bucketName, String fileName, String savePath) throws InterruptedException {
        //文件存储的路径
        File localDownFile = new File(savePath);
        COSConfig config = new COSConfig();
        COSClient client = config.getCosClient();
        GetObjectRequest getObjectRequest = new GetObjectRequest(config.generateBucketId(bucketName), fileName);
        //线程池大小，建议在客户端与 COS 网络充足（例如使用腾讯云的 CVM，同地域上传 COS）的情况下，设置成16或32即可，可较充分的利用网络资源
        //对于使用公网传输且网络带宽质量不高的情况，建议减小该值，避免因网速过慢，造成请求超时。
        ExecutorService threadPool = Executors.newFixedThreadPool(ConstantAttribute.COS_DOWN_THREAD_POOL_SIZE);
        TransferManager transferManager = new TransferManager(client, threadPool);
        Download download = transferManager.download(
                getObjectRequest, localDownFile,
                true, null,
                ConstantAttribute.COS_DOWN_MULTI_THREAD_THRESHOLD,
                ConstantAttribute.COS_DOWN_PART_SIZE);
        COSTaskThreadPool.threadPoolExecutor.execute(new UDTransferProgress(download));
        download.waitForCompletion();
        transferManager.shutdownNow();
    }

}
